import { ref, computed } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { type PageInfo } from '@/config/types'
import api from '@/api/lesson'
import cfg from '@/config/config'
import type {
  CategoryItem,
  LessonListItem,
  LessonDetail,
  ChapterItem,
  EbookItem
} from '@/config/types'
import type { LessonSearchForm } from '@/config/form'

export const useLessonStore = defineStore('lessonStore', () => {
  const loading = ref<boolean>(false)
  const categories = ref<CategoryItem[]>([])
  const searchForm = ref<LessonSearchForm>({
    categoryId: 0,
    title: '',
    sortOption: '',
    sort: '',
    sortDirect: ''
  })
  const lessons = ref<LessonListItem[]>([])
  const pageInfo = ref<PageInfo>({
    page: 1,
    limit: cfg.pageSize,
    total: 0
  })

  const lessonDetail = ref<LessonDetail>({
    id: 0,
    title: '',
    thumb: '',
    categoryId: 0,
    categoryTitle: '',
    price: 0,
    marketPrice: 0,
    summary: '',
    content: '',
    teachers: '',
    isBuyed: false
  })
  const lessonChapters = ref<ChapterItem[]>([])
  const lessonEbooks = ref<EbookItem[]>([])

  const categoryOptions = computed(() => {
    const options = []
    categories.value.forEach((item: CategoryItem) => {
      if (item.children && item.children.length > 0) {
        item.children.forEach((child: CategoryItem) => {
          options.push({
            text: child.title,
            value: child.id
          })
        })
      }
    })
    options.unshift({
      text: '全部课程',
      value: 0
    })
    return options
  })

  const sortOptions = computed(() => {
    return [
      {
        text: '默认排序',
        value: ''
      },
      {
        text: '价格升序',
        value: 'price:asc'
      },
      {
        text: '价格降序',
        value: 'price:desc'
      }
    ]
  })

  async function getCategories() {
    loading.value = true
    try {
      const res = await api.categories()
      categories.value = res.data
    } finally {
      loading.value = false
    }
  }

  async function loadLessonList() {
    loading.value = true
    try {
      formatSort()
      const res = await api.searchList(searchForm.value, pageInfo.value)
      lessons.value = res.data
      pageInfo.value = {
        page: res.page,
        limit: res.size,
        total: res.total
      }
    } finally {
      loading.value = false
    }
  }

  function formatSort() {
    const sort = searchForm.value.sortOption
    if (sort === '') {
      searchForm.value.sort = ''
      searchForm.value.sortDirect = ''
      return
    }

    const arr = searchForm.value.sortOption.split(':')
    if (arr.length == 2) {
      searchForm.value.sort = arr[0]
      searchForm.value.sortDirect = arr[1]
    }
  }

  function lessonSearch() {
    pageInfo.value.page = 1
    loadLessonList()
  }

  function changePage(page: number) {
    pageInfo.value.page = page
    loadLessonList()
  }

  async function loadDetail(id: number) {
    loading.value = true
    try {
      const res = await api.detail(id)
      lessonDetail.value = res.data
    } finally {
      loading.value = false
    }
  }

  async function getChapters(id: number) {
    loading.value = true
    try {
      const res = await api.chapters(id)
      lessonChapters.value = res.data
    } finally {
      loading.value = false
    }
  }

  async function getEbooks(id: number) {
    loading.value = true
    try {
      const res = await api.ebooks(id)
      lessonEbooks.value = res.data
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    searchForm,
    categories,
    lessons,
    pageInfo,
    categoryOptions,
    sortOptions,

    getCategories,
    loadLessonList,
    lessonSearch,
    changePage,

    lessonDetail,
    lessonChapters,
    lessonEbooks,
    loadDetail,
    getChapters,
    getEbooks
  }
})
